package com.bwie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.pojo.TbGroupJoin;
import com.bwie.service.TbGroupJoinService;
import com.bwie.mapper.TbGroupJoinMapper;
import com.bwie.utils.R;
import com.bwie.vo.PageInfoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;


@Service
public class TbGroupJoinServiceImpl extends ServiceImpl<TbGroupJoinMapper, TbGroupJoin>
    implements TbGroupJoinService{
    @Autowired
    TbGroupJoinMapper tbGroupJoinMapper;
    @Autowired
    HttpServletRequest request;

    @Override
    public R getGroupJoinPage(PageInfoVo pageInfoVo) {
        Page<TbGroupJoin> page = new Page<>(pageInfoVo.getPageNum(), pageInfoVo.getPageSize());

        Page<TbGroupJoin> tbGroupJoinPage = tbGroupJoinMapper.getGroupJoinPage(page, pageInfoVo);
        return R.OK(tbGroupJoinPage);
    }

    @Override
    public R addGroupJoin(TbGroupJoin tbGroupJoin) {
        String token = request.getHeader("token");
        if(token == null){
            return R.ERROR(404,"请先登录");
        }


        TbGroupJoin groupJoin = tbGroupJoinMapper.selectOne(
                new LambdaQueryWrapper<TbGroupJoin>().eq(TbGroupJoin::getJoinName, tbGroupJoin.getJoinName())
        );
        if(groupJoin != null){
            return R.ERROR(500,"该拼团活动已经存在");
        }

        long begin = tbGroupJoin.getBeginTime().getTime();
        long end = tbGroupJoin.getEndTime().getTime();
        if(begin>end){
            R.ERROR(500,"开始时间不能晚于截止时间");
        }

        tbGroupJoin.setCreateBy("系统");
        tbGroupJoin.setCreateTime(new Date());

        tbGroupJoinMapper.insert(tbGroupJoin);

        return R.OK();
    }

    @Override
    public R updateGroupJoin(TbGroupJoin tbGroupJoin) {
        String token = request.getHeader("token");
        if(token == null){
            return R.ERROR(404,"请先登录");
        }


        long begin = tbGroupJoin.getBeginTime().getTime();
        long end = tbGroupJoin.getEndTime().getTime();
        if(begin>end){
            R.ERROR(500,"开始时间不能晚于截止时间");
        }

        tbGroupJoin.setUpdateBy("系统");
        tbGroupJoin.setUpdateTime(new Date());

        tbGroupJoinMapper.updateById(tbGroupJoin);

        return R.OK();
    }

    @Override
    public R deleteGroupJoin(Integer joinId) {
        TbGroupJoin tbGroupJoin = tbGroupJoinMapper.selectById(joinId);
        if(tbGroupJoin == null){
            return R.ERROR(404,"该团不存在");
        }

        tbGroupJoinMapper.deleteById(joinId);
        return R.OK();
    }
}




